package option

import (
	"context"
	"strings"

	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/product/rpc/productclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateAttributeOptionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateAttributeOptionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAttributeOptionLogic {
	return &CreateAttributeOptionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateAttributeOptionLogic) CreateAttributeOption(req *types.CreateAttributeOptionReq) (resp *types.BaseMsgResp, err error) {
	if req.Name == nil || len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "attribute.optionNameRequired"))
	}

	adminId := jwt.GetBackendUserId(l.ctx)

	res, err := l.svcCtx.ProductRpc.CreateAttributeOption(l.ctx, &productclient.AttributeOptionInfo{
		AttributeId: req.AttributeId,
		Name:        req.Name,
		Slug:        req.Slug,
		Sort:        req.Sort,
		Status:      req.Status,
		CreatedBy:   pointy.GetPointer(adminId),
	})
	if err != nil {
		return nil, err
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
